package com.tping.finals;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信路由网关
 */
public class SrmRouter {

    // 短信网关对象，通过volatile修饰保存多线程的可见性
    private static volatile SrmRouter instance = new SrmRouter();

    // 短信服务商map, key表是服务商的优先级
    private final Map<Integer, SrmInfo> srmInfoMapRouter;

    // 初始化短信路由网关信息
    public SrmRouter(){
        srmInfoMapRouter = this.loadSrmInfoMapRouter();
    }

    public static SrmRouter getInstance(){
        return instance;
    }

    public static void setInstance(SrmRouter newInstance){
        instance = newInstance;
    }

    /**
     * 服务商信息，可以通过数据加载进来
     *
     * @return
     */
    private Map<Integer, SrmInfo> loadSrmInfoMapRouter() {
        Map<Integer, SrmInfo> infoMap = new HashMap<>();
        infoMap.put(1, new SrmInfo(1L, "https://baidu.yun.com", 128L));
        infoMap.put(2, new SrmInfo(2L, "https://aliyun.com", 128L));
        infoMap.put(3, new SrmInfo(3L, "https://tx.yun.com", 128L));
        return infoMap;
    }

    public Map<Integer, SrmInfo> getSrmInfoMapRouter(){
        // 防止对短信服务商信息修改，添加防御性的复制
        return Collections.unmodifiableMap(deepCopy(this.srmInfoMapRouter));
    }

    private Map<Integer, SrmInfo> deepCopy(Map<Integer, SrmInfo> srmInfoMapRouter) {
        Map<Integer, SrmInfo> hashMap = new HashMap<>(srmInfoMapRouter.size());
        for ( Map.Entry<Integer, SrmInfo> entry : srmInfoMapRouter.entrySet() ){
            hashMap.put(entry.getKey(), new SrmInfo(entry.getValue()));
        }
        return hashMap;
    }

    public void changeRouterInfo(){
        // 更新短信服务商的信息
        // updateSrmRouterInfoList();

        // 更新内存中短信服务商信息
        SrmRouter.setInstance(new SrmRouter());
    }
}
